package cn.wolfcode.shop.cloud.servive.impl;

import cn.wolfcode.shop.cloud.common.BusinessException;
import cn.wolfcode.shop.cloud.domain.User;
import cn.wolfcode.shop.cloud.mapper.UserMapper;
import cn.wolfcode.shop.cloud.msg.MemberCodeMsg;
import cn.wolfcode.shop.cloud.service.RedisService;
import cn.wolfcode.shop.cloud.servive.IUserService;
import cn.wolfcode.shop.cloud.util.Md5Util;
import cn.wolfcode.shop.cloud.util.MemberKeyPrefix;
import cn.wolfcode.shop.cloud.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;

@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisService redisService;


    @Override
    public User get(Long id) {
        User user = userMapper.findById(id);
        return user;
    }

    @Override
    public String doLogin(LoginVo loginVo) {
        if (StringUtils.isEmpty(loginVo.getUsername()) || StringUtils.isEmpty(loginVo.getPassword())) {
            throw new BusinessException(MemberCodeMsg.USERNAME_AND_PASSWORD_NOT_NULL);
        }
        //手机号码
        long id = Long.parseLong(loginVo.getUsername());

        User user = get(id);
        if (user == null) {
            //该用户不存在
            throw new BusinessException(MemberCodeMsg.USER_NOT_EXISTS);
        }
        String endByPass = Md5Util.endCode(user.getSalt(), loginVo.getPassword());
        if (!endByPass.equals(user.getPassword())) {
            //账号和密码不匹配
            throw new BusinessException(MemberCodeMsg.PASSWORD_ERROR);
        }

        String token = createToken(user);
        return token;
    }

    @Override
    //存在刷新获取feign返回的true和false
    public Boolean refreshRedisToken(String token) {
        //如果key存在
        boolean flag = redisService.exists(MemberKeyPrefix.USER_TOKEN, token);
        if (flag) {
            redisService.expire(MemberKeyPrefix.USER_TOKEN, token);
            return true;
        }
        return false;
    }

    @Override
    //查看用户是否登录
    public User getCurrent(String token) {
        if(StringUtils.isEmpty(token)){
            return null;
        }
        return redisService.get(MemberKeyPrefix.USER_TOKEN,token,User.class);
    }

    private String createToken(User user) {
        //生成Token
        String token = UUID.randomUUID().toString().replace("-", "");
        //放到redis中存储起来
        redisService.set(MemberKeyPrefix.USER_TOKEN, token, user);
        return token;
    }
}